using UnityEngine;

public class EnemyController : MonoBehaviour
{
    [Header("基础属性")]
    public int health = 3;
    public int maxHealth = 3;
    public float moveSpeed = 3f;
    public int scoreValue = 100;
    
    [Header("移动模式")]
    public MovementPattern movementPattern = MovementPattern.StraightDown;
    public float amplitude = 2f; // 正弦波振幅
    public float frequency = 1f; // 正弦波频率
    
    [Header("攻击设置")]
    public GameObject enemyBulletPrefab;
    public Transform firePoint;
    public float fireRate = 1f;
    public float bulletSpeed = 8f;
    public bool canAttack = true;
    
    [Header("视觉效果")]
    public Color normalColor = Color.white;
    public Color hitColor = Color.red;
    public float hitFlashDuration = 0.1f;
    
    [Header("调试设置")]
    public bool showDebugInfo = false;
    
    // 对象池相关
    private EnemySpawner enemySpawner;
    
    private Vector3 startPosition;
    private float timeAlive;
    private float nextFireTime;
    private SpriteRenderer spriteRenderer;
    private bool isFlashing;
    private float flashTimer;
    
    public enum MovementPattern
    {
        StraightDown,   // 直线下降
        SineWave,       // 正弦波
        Zigzag,         // 锯齿形
        Circular        // 圆形轨迹
    }
    
    void Start()
    {
        startPosition = transform.position;
        health = maxHealth;
        
        spriteRenderer = GetComponent<SpriteRenderer>();
        if (spriteRenderer == null)
        {
            spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
            spriteRenderer.sprite = CreateEnemySprite();
        }
        
        spriteRenderer.color = normalColor;
        
        // 设置碰撞器
        if (GetComponent<Collider2D>() == null)
        {
            CircleCollider2D collider = gameObject.AddComponent<CircleCollider2D>();
            collider.radius = 0.3f;
            collider.isTrigger = true;
        }
        
        // 创建发射点
        if (firePoint == null)
        {
            GameObject firePointObj = new GameObject("EnemyFirePoint");
            firePointObj.transform.SetParent(transform);
            firePointObj.transform.localPosition = Vector3.down * 0.3f;
            firePoint = firePointObj.transform;
        }
        
        // 创建默认子弹预制体
        if (enemyBulletPrefab == null)
        {
            CreateDefaultEnemyBullet();
        }
        
        // 设置标签
        gameObject.tag = "Enemy";
        
        Debug.Log($"敌人已生成: 生命值={health}, 移动模式={movementPattern}");
    }
    
    void Update()
    {
        timeAlive += Time.deltaTime;
        
        HandleMovement();
        HandleAttack();
        HandleVisualEffects();
        CheckBoundaries();
        
        if (showDebugInfo)
        {
            Debug.Log($"敌人状态: 生命值={health}, 位置={transform.position}, 存活时间={timeAlive:F1}s");
        }
    }
    
    void HandleMovement()
    {
        Vector3 movement = Vector3.zero;
        
        switch (movementPattern)
        {
            case MovementPattern.StraightDown:
                movement = Vector3.down * moveSpeed * Time.deltaTime;
                break;
                
            case MovementPattern.SineWave:
                float sineOffset = Mathf.Sin(timeAlive * frequency) * amplitude;
                Vector3 targetPos = startPosition + Vector3.right * sineOffset + Vector3.down * timeAlive * moveSpeed;
                transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
                return;
                
            case MovementPattern.Zigzag:
                float zigzagOffset = Mathf.PingPong(timeAlive * frequency, amplitude * 2) - amplitude;
                movement = (Vector3.right * zigzagOffset + Vector3.down * moveSpeed) * Time.deltaTime;
                break;
                
            case MovementPattern.Circular:
                float angle = timeAlive * frequency;
                Vector3 circularOffset = new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0) * amplitude;
                Vector3 circularTarget = startPosition + circularOffset + Vector3.down * timeAlive * moveSpeed * 0.5f;
                transform.position = Vector3.MoveTowards(transform.position, circularTarget, moveSpeed * Time.deltaTime);
                return;
        }
        
        transform.position += movement;
    }
    
    void HandleAttack()
    {
        if (!canAttack || enemyBulletPrefab == null || firePoint == null) return;
        
        if (Time.time >= nextFireTime)
        {
            FireBullet();
            nextFireTime = Time.time + fireRate;
        }
    }
    
    void FireBullet()
    {
        GameObject bullet = Instantiate(enemyBulletPrefab, firePoint.position, Quaternion.identity);
        // 若模板为非激活状态，确保克隆体被激活
        if (!bullet.activeSelf)
        {
            bullet.SetActive(true);
        }
        
        BulletController bulletController = bullet.GetComponent<BulletController>();
        if (bulletController != null)
        {
            // 朝玩家方向射击
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            Vector2 direction = Vector2.down; // 默认向下
            
            if (player != null)
            {
                direction = (player.transform.position - firePoint.position).normalized;
            }
            
            bulletController.SetDirection(direction);
            bulletController.SetSpeed(bulletSpeed);
            bulletController.SetBulletType(BulletController.BulletType.Enemy);
        }
        
        // 设置子弹的父对象
        bullet.transform.SetParent(GameObject.Find("EnemyBullets")?.transform);
        
        if (showDebugInfo)
        {
            Debug.Log($"敌人发射子弹: 位置={firePoint.position}");
        }
    }
    
    void HandleVisualEffects()
    {
        if (isFlashing)
        {
            flashTimer -= Time.deltaTime;
            
            if (flashTimer <= 0)
            {
                isFlashing = false;
                spriteRenderer.color = normalColor;
            }
        }
    }
    
    void CheckBoundaries()
    {
        if (BoundaryManager.Instance != null && BoundaryManager.Instance.IsOutOfBounds(transform.position))
        {
            // 敌人超出边界，销毁
            DestroyEnemy(false);
        }
    }
    
    public void TakeDamage(int damage)
    {
        health -= damage;
        
        // 受伤闪烁效果
        isFlashing = true;
        flashTimer = hitFlashDuration;
        spriteRenderer.color = hitColor;
        
        Debug.Log($"敌人受到伤害: {damage}, 剩余生命值: {health}");
        
        if (health <= 0)
        {
            DestroyEnemy(true);
        }
    }
    
    void DestroyEnemy(bool giveScore)
    {
        if (giveScore)
        {
            // 这里可以添加分数系统
            Debug.Log($"敌人被击败，获得分数: {scoreValue}");
            
            // 创建爆炸效果
            CreateDestroyEffect();
        }
        
        Debug.Log($"敌人已销毁: {gameObject.name}");
        
        if (enemySpawner != null)
        {
            enemySpawner.ReturnEnemyToPool(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    void CreateDestroyEffect()
    {
        GameObject effect = new GameObject("EnemyDestroyEffect");
        effect.transform.position = transform.position;
        
        ParticleSystem particles = effect.AddComponent<ParticleSystem>();
        var main = particles.main;
        main.startLifetime = 1f;
        main.startSpeed = 8f;
        main.startSize = 0.2f;
        main.startColor = new Color(1f, 0.5f, 0f); // 橙色
        main.maxParticles = 20;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0.0f, 20)
        });
        
        var shape = particles.shape;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 0.5f;
        
        Destroy(effect, 2f);
    }
    
    void CreateDefaultEnemyBullet()
    {
        GameObject bullet = new GameObject("DefaultEnemyBullet");
        
        SpriteRenderer sr = bullet.AddComponent<SpriteRenderer>();
        sr.sprite = CreateBulletSprite();
        sr.color = Color.red;
        
        CircleCollider2D collider = bullet.AddComponent<CircleCollider2D>();
        collider.radius = 0.08f;
        collider.isTrigger = true;
        
        Rigidbody2D rb = bullet.AddComponent<Rigidbody2D>();
        rb.gravityScale = 0f;
        
        bullet.AddComponent<BulletController>();
        bullet.tag = "EnemyBullet";
        
        // 将此对象作为模板使用，不应在场景中运行
        bullet.SetActive(false);
        // 可选：减少层级干扰（仅编辑器可见性）
        bullet.hideFlags |= HideFlags.HideInHierarchy;

        enemyBulletPrefab = bullet;
    }
    
    Sprite CreateEnemySprite()
    {
        Texture2D texture = new Texture2D(32, 32);
        Color[] pixels = new Color[32 * 32];
        
        for (int i = 0; i < pixels.Length; i++)
        {
            int x = i % 32;
            int y = i / 32;
            
            // 创建简单的敌人形状
            if ((x >= 8 && x <= 24 && y >= 12 && y <= 20) || 
                (x >= 12 && x <= 20 && y >= 8 && y <= 24))
            {
                pixels[i] = Color.red;
            }
            else
            {
                pixels[i] = Color.clear;
            }
        }
        
        texture.SetPixels(pixels);
        texture.Apply();
        
        return Sprite.Create(texture, new Rect(0, 0, 32, 32), new Vector2(0.5f, 0.5f));
    }
    
    Sprite CreateBulletSprite()
    {
        Texture2D texture = new Texture2D(12, 12);
        Color[] pixels = new Color[12 * 12];
        
        for (int i = 0; i < pixels.Length; i++)
        {
            int x = i % 12;
            int y = i / 12;
            float distance = Vector2.Distance(new Vector2(x, y), new Vector2(6, 6));
            
            if (distance <= 4)
            {
                pixels[i] = Color.white;
            }
            else
            {
                pixels[i] = Color.clear;
            }
        }
        
        texture.SetPixels(pixels);
        texture.Apply();
        
        return Sprite.Create(texture, new Rect(0, 0, 12, 12), new Vector2(0.5f, 0.5f));
    }
    
    void OnDrawGizmos()
    {
        if (showDebugInfo)
        {
            // 绘制移动路径预览
            Gizmos.color = Color.yellow;
            
            switch (movementPattern)
            {
                case MovementPattern.SineWave:
                    for (float t = 0; t < 5f; t += 0.1f)
                    {
                        float sineOffset = Mathf.Sin(t * frequency) * amplitude;
                        Vector3 pos = startPosition + Vector3.right * sineOffset + Vector3.down * t * moveSpeed;
                        Gizmos.DrawWireSphere(pos, 0.1f);
                    }
                    break;
            }
            
            // 绘制攻击范围
            if (firePoint != null)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawWireSphere(firePoint.position, 0.1f);
            }
        }
    }
    
    public void SetEnemySpawner(EnemySpawner spawner)
    {
        enemySpawner = spawner;
    }
}